from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import stripe
import os
import logging
from pydantic import BaseModel
from typing import Optional, Dict, Any, List

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 初始化FastAPI应用
app = FastAPI(title="Stripe Connect Account API", description="用户A通过平台向用户B付款")

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 配置Stripe
STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY", "sk_test_your_test_key")
STRIPE_PUBLIC_KEY = os.getenv("STRIPE_PUBLIC_KEY", "pk_test_your_public_key")
STRIPE_WEBHOOK_SECRET = os.getenv("STRIPE_WEBHOOK_SECRET", "whsec_your_webhook_secret")

stripe.api_key = "sk_test_51Ogsw5B0IyqaSJBrwczlr820jnmvA1qQQGoLZ2XxOsIzikpmXo4pRLjw4XVMTEBR8DdVTYySiAv1XX53Zv5xqynF00GfMqttFd"

# 模拟数据库 - 实际项目中替换为真实数据库
connect_accounts_db: Dict[str, Dict[str, Any]] = {}  # Connect账户信息
transfers_db: Dict[str, Dict[str, Any]] = {}  # 转账记录
customers_db: Dict[str, Dict[str, Any]] = {}  # 客户信息


# 请求模型
class CreateConnectAccountRequest(BaseModel):
    email: str
    business_type: str = "individual"  # individual 或 company
    country: str = "US"
    capabilities: Dict[str, str] = {"card_payments": "active", "transfers": "active"}
    business_profile: Optional[Dict[str, Any]] = None


class CreatePaymentRequest(BaseModel):
    amount: int  # 金额（以分为单位）
    currency: str = "usd"
    connect_account_id: str  # 收款方Connect账户ID
    customer_email: Optional[str] = None
    description: Optional[str] = None
    metadata: Optional[Dict[str, str]] = None


class CreateTransferRequest(BaseModel):
    amount: int  # 转账金额（以分为单位）
    currency: str = "usd"
    destination: str  # Connect账户ID
    description: Optional[str] = None
    metadata: Optional[Dict[str, str]] = None


class CreatePaymentMethodRequest(BaseModel):
    """创建支付方式的请求模型"""
    type: str = "card"  # 支付方式类型，默认为card
    card: Optional[Dict[str, Any]] = None  # 卡片信息
    billing_details: Optional[Dict[str, Any]] = None  # 账单详情
    use_test_token: bool = True  # 是否使用测试令牌（推荐用于测试）


class ConfirmCardPaymentRequest(BaseModel):
    """确认卡片支付的请求模型"""
    payment_intent_id: str  # 支付意图ID
    payment_method_id: str  # 支付方式ID


class RetrievePaymentIntentRequest(BaseModel):
    """获取支付意图详情的请求模型"""
    payment_intent_id: str  # 支付意图ID


# 创建Connect账户（收款方）
@app.post("/create-connect-account")
async def create_connect_account(request: CreateConnectAccountRequest):
    """为收款方创建Stripe Connect账户"""
    try:
        # 先检查本地数据库中是否已存在相同邮箱的Connect账户
        existing_account_id = None
        for account_id, account_data in connect_accounts_db.items():
            if account_data.get('email') == request.email:
                existing_account_id = account_id
                break
        
        # 同时检查Stripe中是否存在相同邮箱的Connect账户
        stripe_existing_account = None
        try:
            # 获取所有Connect账户并查找匹配的邮箱
            stripe_accounts = stripe.Account.list(limit=100)  # 获取前100个账户
            for account in stripe_accounts.data:
                if account.email == request.email:
                    stripe_existing_account = account
                    logger.info(f"在Stripe中找到已存在的Connect账户: {account.id} 邮箱: {request.email}")
                    break
        except stripe.error.StripeError as e:
            logger.warning(f"查询Stripe账户时出错: {e}")
        
        # 如果本地数据库或Stripe中找到已存在的账户
        if existing_account_id or stripe_existing_account:
            # 优先使用Stripe中找到的账户，否则使用本地数据库中的账户
            target_account = stripe_existing_account if stripe_existing_account else None
            
            if not target_account and existing_account_id:
                try:
                    target_account = stripe.Account.retrieve(existing_account_id)
                except stripe.error.StripeError as e:
                    logger.warning(f"无法获取本地账户信息: {e}")
                    target_account = None
            
            if target_account:
                logger.info(f"找到已存在的Connect账户: {target_account.id} 邮箱: {request.email}")
                
                # 更新本地数据库
                connect_accounts_db[target_account.id] = {
                    "id": target_account.id,
                    "email": target_account.email,
                    "country": target_account.country,
                    "business_type": getattr(target_account, 'business_type', None),
                    "charges_enabled": target_account.charges_enabled,
                    "payouts_enabled": target_account.payouts_enabled,
                    "created_at": target_account.created,
                    "status": "active" if target_account.charges_enabled else "pending"
                }
                
                return {
                    "account_id": target_account.id,
                    "account_link": None,  # 已存在的账户不需要设置链接
                    "email": target_account.email,
                    "status": "active" if target_account.charges_enabled else "pending",
                    "message": "找到已存在的Connect账户",
                    "source": "stripe" if stripe_existing_account else "local_database"
                }
            else:
                logger.warning(f"找到账户记录但无法获取详细信息，继续创建新账户")
                pass
        
        # 如果不存在，则创建新的Connect账户
        logger.info(f"未找到相同邮箱的Connect账户，开始创建新账户: {request.email}")
        
        account = stripe.Account.create(
            type="express",  # 使用Express账户类型，简化流程
            country=request.country,
            email=request.email,
            # capabilities=request.capabilities,
            # business_type=request.business_type,
            # business_profile=request.business_profile or {
            #     "url": "https://example.com",
            #     "mcc": "5734"  # 计算机软件商店
            # }
        )

        # 保存到本地数据库
        connect_accounts_db[account.id] = {
            "id": account.id,
            "email": account.email,
            "country": account.country,
            "business_type": account.business_type,
            "charges_enabled": account.charges_enabled,
            "payouts_enabled": account.payouts_enabled,
            "created_at": account.created,
            "status": "pending"
        }

        logger.info(f"创建Connect账户: {account.id} 邮箱: {account.email}")
        return {
            "account_id": account.id,
            "account_link": account.links.express.url if hasattr(account, 'links') else None,
            "email": account.email,
            "status": "pending"
        }

    except stripe.error.StripeError as e:
        logger.error(f"Stripe错误: {str(e)}")
        raise HTTPException(status_code=400, detail=f"创建Connect账户失败: {str(e)}")
    except Exception as e:
        logger.error(f"服务器错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


# 获取Connect账户链接（用于完成账户设置）
@app.get("/account-link/{account_id}")
async def get_account_link(account_id: str):
    """获取Connect账户设置链接"""
    try:
        # 检查账户是否存在
        # if account_id not in connect_accounts_db:
        #     raise HTTPException(status_code=404, detail="Connect账户不存在")

        # 创建账户链接
        account_link = stripe.AccountLink.create(
            account=account_id,
            refresh_url="http://localhost:8002/account/{}".format(account_id),
            return_url="http://localhost:8002/account/{}".format(account_id),
            type="account_onboarding"
        )

        return {
            "account_id": account_id,
            "url": account_link.url,
            "expires_at": account_link.expires_at
        }

    except stripe.error.StripeError as e:
        logger.error(f"Stripe错误: {str(e)}")
        raise HTTPException(status_code=400, detail=f"获取账户链接失败: {str(e)}")


# 确认付款
@app.post("/confirm-payment")
async def confirm_payment(request: Request):
    """确认支付意图"""
    try:
        body = await request.json()
        payment_intent_id = body.get("payment_intent_id")
        payment_method_id = body.get("payment_method_id")
        
        if not payment_intent_id or not payment_method_id:
            raise HTTPException(status_code=400, detail="缺少必要参数: payment_intent_id 和 payment_method_id")
        
        # 确认支付意图
        payment_intent = stripe.PaymentIntent.confirm(
            payment_intent_id,
            payment_method=payment_method_id,
            return_url="http://localhost:8002/payment/return"  # 添加返回URL
        )

        logger.info(f"确认付款: {payment_intent_id} 状态: {payment_intent.status}")
        
        return {
            "payment_intent_id": payment_intent.id,
            "status": payment_intent.status,
            "amount": payment_intent.amount,
            "currency": payment_intent.currency,
            "client_secret": payment_intent.client_secret
        }

    except stripe.error.StripeError as e:
        logger.error(f"Stripe错误: {str(e)}")
        raise HTTPException(status_code=400, detail=f"确认付款失败: {str(e)}")
    except Exception as e:
        logger.error(f"服务器错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


# 创建支付方式
@app.post("/create-payment-method")
async def create_payment_method(request: CreatePaymentMethodRequest):
    """
    创建支付方式接口
    
    前端调用目的：
    - 将用户输入的信用卡信息转换为Stripe支付方式对象
    - 避免在前端直接处理敏感的信用卡数据
    - 为后续的支付确认做准备
    
    使用场景：
    - 用户填写信用卡信息后，需要创建支付方式
    - 支付方式创建成功后，可以用于确认支付意图
    """
    try:
        # 创建支付方式参数
        payment_method_data = {
            "type": request.type
        }
        
        if request.card:
            if request.use_test_token:
                # 使用测试令牌（推荐用于测试环境）
                card_number = request.card.get("number", "")
                if card_number.startswith("4242424242424242"):
                    payment_method_data["card"] = {"token": "tok_visa"}
                elif card_number.startswith("4000002500003155"):
                    payment_method_data["card"] = {"token": "tok_visa_debit"}
                elif card_number.startswith("5555555555554444"):
                    payment_method_data["card"] = {"token": "tok_mastercard"}
                elif card_number.startswith("378282246310005"):
                    payment_method_data["card"] = {"token": "tok_amex"}
                elif card_number.startswith("4000000000000002"):
                    payment_method_data["card"] = {"token": "tok_chargeDeclined"}
                elif card_number.startswith("4000000000009995"):
                    payment_method_data["card"] = {"token": "tok_chargeDeclinedInsufficientFunds"}
                else:
                    # 默认使用Visa测试令牌
                    payment_method_data["card"] = {"token": "tok_visa"}
            else:
                # 使用原始卡片数据（需要启用原始卡片数据API）
                payment_method_data["card"] = request.card
        
        if request.billing_details:
            payment_method_data["billing_details"] = request.billing_details
        
        # 调用Stripe API创建支付方式
        payment_method = stripe.PaymentMethod.create(**payment_method_data)
        
        logger.info(f"创建支付方式成功: {payment_method.id}")
        
        return {
            "payment_method_id": payment_method.id,
            "type": payment_method.type,
            "card": {
                "brand": payment_method.card.brand if payment_method.card else None,
                "last4": payment_method.card.last4 if payment_method.card else None,
                "exp_month": payment_method.card.exp_month if payment_method.card else None,
                "exp_year": payment_method.card.exp_year if payment_method.card else None
            } if payment_method.card else None,
            "billing_details": payment_method.billing_details
        }
        
    except stripe.error.StripeError as e:
        logger.error(f"Stripe错误: {str(e)}")
        raise HTTPException(status_code=400, detail=f"创建支付方式失败: {str(e)}")
    except Exception as e:
        logger.error(f"服务器错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


# 获取支付意图详情
@app.get("/payment-intent/{payment_intent_id}")
async def get_payment_intent(payment_intent_id: str):
    """
    获取支付意图详情接口
    
    前端调用目的：
    - 查询支付意图的当前状态
    - 获取支付意图的详细信息
    - 用于支付状态轮询和显示
    
    使用场景：
    - 支付完成后查询支付状态
    - 显示支付详情信息
    - 处理支付失败的情况
    """
    try:
        # 从Stripe获取支付意图详情
        payment_intent = stripe.PaymentIntent.retrieve(payment_intent_id)
        
        logger.info(f"获取支付意图详情: {payment_intent_id} 状态: {payment_intent.status}")
        
        return {
            "payment_intent_id": payment_intent.id,
            "amount": payment_intent.amount,
            "currency": payment_intent.currency,
            "status": payment_intent.status,
            "client_secret": payment_intent.client_secret,
            "payment_method": payment_intent.payment_method,
            "transfer_data": payment_intent.transfer_data,
            "application_fee_amount": payment_intent.application_fee_amount,
            "created": payment_intent.created,
            "last_payment_error": payment_intent.last_payment_error
        }
        
    except stripe.error.StripeError as e:
        logger.error(f"Stripe错误: {str(e)}")
        raise HTTPException(status_code=400, detail=f"获取支付意图详情失败: {str(e)}")
    except Exception as e:
        logger.error(f"服务器错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


# 支付返回页面
@app.get("/payment/return")
async def payment_return(session_id: Optional[str] = None):
    """
    支付完成后的返回页面
    
    前端调用目的：
    - 处理支付完成后的重定向
    - 显示支付结果
    - 提供用户友好的反馈
    
    使用场景：
    - 3D Secure认证完成后重定向
    - 支付成功或失败后的用户反馈
    """
    try:
        if session_id:
            # 获取支付意图详情
            payment_intent = stripe.PaymentIntent.retrieve(session_id)
            status = payment_intent.status
            
            if status == "succeeded":
                return {
                    "status": "success",
                    "message": "支付成功！",
                    "payment_intent_id": payment_intent.id,
                    "amount": payment_intent.amount,
                    "currency": payment_intent.currency
                }
            elif status == "requires_payment_method":
                return {
                    "status": "failed",
                    "message": "支付失败，请重试",
                    "payment_intent_id": payment_intent.id
                }
            else:
                return {
                    "status": "pending",
                    "message": f"支付状态: {status}",
                    "payment_intent_id": payment_intent.id
                }
        else:
            return {
                "status": "unknown",
                "message": "无法获取支付信息"
            }
            
    except stripe.error.StripeError as e:
        logger.error(f"Stripe错误: {str(e)}")
        return {
            "status": "error",
            "message": f"获取支付信息失败: {str(e)}"
        }
    except Exception as e:
        logger.error(f"服务器错误: {str(e)}")
        return {
            "status": "error",
            "message": "服务器内部错误"
        }


# 确认卡片支付（处理3D Secure）
@app.post("/confirm-card-payment")
async def confirm_card_payment(request: ConfirmCardPaymentRequest):
    """
    确认卡片支付接口（处理3D Secure认证）
    
    前端调用目的：
    - 处理需要3D Secure认证的支付
    - 完成支付确认流程
    - 处理支付结果和错误
    
    使用场景：
    - 支付意图状态为requires_action时
    - 需要3D Secure认证的信用卡支付
    - 处理支付确认的最终步骤
    """
    try:
        # 确认卡片支付
        payment_intent = stripe.PaymentIntent.confirm(
            request.payment_intent_id,
            payment_method=request.payment_method_id,
            return_url="http://localhost:8002/payment/return"  # 添加返回URL
        )
        
        logger.info(f"确认卡片支付: {request.payment_intent_id} 状态: {payment_intent.status}")
        
        return {
            "payment_intent_id": payment_intent.id,
            "status": payment_intent.status,
            "amount": payment_intent.amount,
            "currency": payment_intent.currency,
            "client_secret": payment_intent.client_secret,
            "next_action": payment_intent.next_action,
            "last_payment_error": payment_intent.last_payment_error
        }
        
    except stripe.error.StripeError as e:
        logger.error(f"Stripe错误: {str(e)}")
        raise HTTPException(status_code=400, detail=f"确认卡片支付失败: {str(e)}")
    except Exception as e:
        logger.error(f"服务器错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


# 创建支付意图（用户A向用户B付款）
@app.post("/create-payment-intent")
async def create_payment_intent(request: CreatePaymentRequest):
    """创建支付意图，用户A向Connect账户付款"""
    try:
        # 检查Connect账户是否存在且已激活
        # if request.connect_account_id not in connect_accounts_db:
        #     raise HTTPException(status_code=404, detail="Connect账户不存在")

        # 获取或创建客户
        customer = None
        if request.customer_email:
            existing_customers = stripe.Customer.list(email=request.customer_email, limit=1).data
            if existing_customers:
                customer = existing_customers[0]
            else:
                customer = stripe.Customer.create(email=request.customer_email)

        # 创建支付意图
        payment_intent = stripe.PaymentIntent.create(
            amount=request.amount,
            currency=request.currency,
            application_fee_amount=int(request.amount * 0.029 + 30),  # 2.9% + 30分平台费用
            transfer_data={
                "destination": request.connect_account_id,
            },
            customer=customer.id if customer else None,
            description=request.description or f"付款给 {request.connect_account_id}",
            metadata=request.metadata or {},
            automatic_payment_methods={
                "enabled": True,
                "allow_redirects": "never"  # 禁止重定向支付方式
            }
        )

        # 保存支付记录
        transfers_db[payment_intent.id] = {
            "payment_intent_id": payment_intent.id,
            "amount": request.amount,
            "currency": request.currency,
            "connect_account_id": request.connect_account_id,
            "customer_id": customer.id if customer else None,
            "status": payment_intent.status,
            "created_at": payment_intent.created,
            "application_fee_amount": int(request.amount * 0.029 + 30)
        }

        logger.info(f"创建支付意图: {payment_intent.id} 金额: {request.amount} {request.currency}")
        return {
            "payment_intent_id": payment_intent.id,
            "client_secret": payment_intent.client_secret,
            "amount": request.amount,
            "currency": request.currency,
            "status": payment_intent.status
        }

    except stripe.error.StripeError as e:
        logger.error(f"Stripe错误: {str(e)}")
        raise HTTPException(status_code=400, detail=f"创建支付意图失败: {str(e)}")
    except Exception as e:
        logger.error(f"服务器错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


# 创建直接转账（平台向Connect账户转账）
@app.post("/create-transfer")
async def create_transfer(request: CreateTransferRequest):
    """平台向Connect账户直接转账"""
    try:
        # 检查Connect账户是否存在
        if request.destination not in connect_accounts_db:
            raise HTTPException(status_code=404, detail="Connect账户不存在")

        # 创建转账
        transfer = stripe.Transfer.create(
            amount=request.amount,
            currency=request.currency,
            destination=request.destination,
            description=request.description or f"转账给 {request.destination}",
            metadata=request.metadata or {}
        )

        # 保存转账记录
        transfers_db[transfer.id] = {
            "transfer_id": transfer.id,
            "amount": request.amount,
            "currency": request.currency,
            "destination": request.destination,
            "status": transfer.status,
            "created_at": transfer.created,
            "type": "transfer"
        }

        logger.info(f"创建转账: {transfer.id} 金额: {request.amount} {request.currency}")
        return {
            "transfer_id": transfer.id,
            "amount": request.amount,
            "currency": request.currency,
            "status": transfer.status,
            "destination": request.destination
        }

    except stripe.error.StripeError as e:
        logger.error(f"Stripe错误: {str(e)}")
        raise HTTPException(status_code=400, detail=f"创建转账失败: {str(e)}")
    except Exception as e:
        logger.error(f"服务器错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


# 获取所有Connect账户列表
@app.get("/accounts")
async def get_all_accounts():
    """获取所有Connect账户列表"""
    try:
        accounts = []
        for account_id, account_data in connect_accounts_db.items():
            # 从Stripe获取最新信息
            try:
                stripe_account = stripe.Account.retrieve(account_id)
                accounts.append({
                    "account_id": stripe_account.id,
                    "email": stripe_account.email,
                    "country": stripe_account.country,
                    "business_type": getattr(stripe_account, 'business_type', None),
                    "charges_enabled": stripe_account.charges_enabled,
                    "payouts_enabled": stripe_account.payouts_enabled,
                    "status": "active" if stripe_account.charges_enabled else "pending"
                })
            except stripe.error.StripeError as e:
                logger.warning(f"无法获取账户 {account_id} 信息: {e}")
                # 使用本地数据
                accounts.append({
                    "account_id": account_data.get("id"),
                    "email": account_data.get("email"),
                    "country": account_data.get("country"),
                    "business_type": account_data.get("business_type"),
                    "charges_enabled": account_data.get("charges_enabled", False),
                    "payouts_enabled": account_data.get("payouts_enabled", False),
                    "status": account_data.get("status", "pending")
                })

        return {"accounts": accounts, "total": len(accounts)}

    except Exception as e:
        logger.error(f"获取账户列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取账户列表失败")


# 获取Connect账户信息
@app.get("/account/{account_id}")
async def get_account_info(account_id: str):
    """获取Connect账户详细信息"""
    try:
        # 从Stripe获取最新账户信息
        account = stripe.Account.retrieve(account_id)

        # 更新本地数据库
        connect_accounts_db[account_id] = {
            "id": account.id,
            "email": account.email,
            "country": account.country,
            "business_type": account.business_type,
            "charges_enabled": account.charges_enabled,
            "payouts_enabled": account.payouts_enabled,
            "created_at": account.created,
            "status": "active" if account.charges_enabled else "pending"
        }

        return {
            "account_id": account.id,
            "email": account.email,
            "country": account.country,
            "business_type": account.business_type,
            "charges_enabled": account.charges_enabled,
            "payouts_enabled": account.payouts_enabled,
            "status": "active" if account.charges_enabled else "pending"
        }

    except stripe.error.StripeError as e:
        logger.error(f"Stripe错误: {str(e)}")
        raise HTTPException(status_code=400, detail=f"获取账户信息失败: {str(e)}")


# 获取转账记录
@app.get("/transfers")
async def get_transfers(account_id: Optional[str] = None, limit: int = 10):
    """获取转账记录"""
    try:
        transfers = []

        if account_id:
            # 获取特定账户的转账记录
            stripe_transfers = stripe.Transfer.list(
                destination=account_id,
                limit=limit
            )
        else:
            # 获取所有转账记录
            stripe_transfers = stripe.Transfer.list(limit=limit)

        for transfer in stripe_transfers.data:
            transfers.append({
                "transfer_id": transfer.id,
                "amount": transfer.amount,
                "currency": transfer.currency,
                "destination": transfer.destination,
                "status": transfer.status,
                "created_at": transfer.created,
                "description": transfer.description
            })

        return {"transfers": transfers, "total": len(transfers)}

    except stripe.error.StripeError as e:
        logger.error(f"Stripe错误: {str(e)}")
        raise HTTPException(status_code=400, detail=f"获取转账记录失败: {str(e)}")


# 获取支付意图记录
@app.get("/payment-intents")
async def get_payment_intents(connect_account_id: Optional[str] = None, limit: int = 10):
    """获取支付意图记录"""
    try:
        payment_intents = []

        if connect_account_id:
            # 获取特定Connect账户的支付意图
            stripe_payment_intents = stripe.PaymentIntent.list(
                transfer_data={"destination": connect_account_id},
                limit=limit
            )
        else:
            # 获取所有支付意图
            stripe_payment_intents = stripe.PaymentIntent.list(limit=limit)

        for pi in stripe_payment_intents.data:
            payment_intents.append({
                "payment_intent_id": pi.id,
                "amount": pi.amount,
                "currency": pi.currency,
                "status": pi.status,
                "created_at": pi.created,
                "transfer_data": pi.transfer_data,
                "application_fee_amount": pi.application_fee_amount
            })

        return {"payment_intents": payment_intents, "total": len(payment_intents)}

    except stripe.error.StripeError as e:
        logger.error(f"Stripe错误: {str(e)}")
        raise HTTPException(status_code=400, detail=f"获取支付意图记录失败: {str(e)}")


# 处理Stripe Webhook事件
@app.post("/stripe-webhook")
async def stripe_webhook(request: Request):
    """处理Stripe Connect相关的Webhook事件"""
    payload = await request.body()
    sig_header = request.headers.get("Stripe-Signature")

    if not sig_header:
        raise HTTPException(status_code=400, detail="缺少Stripe-Signature头")

    try:
        # 验证Webhook签名
        event = stripe.Webhook.construct_event(
            payload=payload,
            sig_header=sig_header,
            secret=STRIPE_WEBHOOK_SECRET
        )
    except ValueError as e:
        logger.error(f"无效的请求体: {str(e)}")
        raise HTTPException(status_code=400, detail="无效的请求体")
    except stripe.error.SignatureVerificationError as e:
        logger.error(f"无效的签名: {str(e)}")
        raise HTTPException(status_code=400, detail="无效的签名")

    # 处理事件
    event_type = event.type
    logger.info(f"收到Stripe事件: {event_type}")

    # 处理账户更新
    if event_type == "account.updated":
        account = event.data.object
        account_id = account.id

        logger.info(f"账户更新: {account_id} 状态: charges_enabled={account.charges_enabled}")

        # 更新本地记录
        if account_id in connect_accounts_db:
            connect_accounts_db[account_id]["charges_enabled"] = account.charges_enabled
            connect_accounts_db[account_id]["payouts_enabled"] = account.payouts_enabled
            connect_accounts_db[account_id]["status"] = "active" if account.charges_enabled else "pending"

    # 处理支付意图成功
    elif event_type == "payment_intent.succeeded":
        payment_intent = event.data.object
        payment_intent_id = payment_intent.id

        logger.info(f"支付成功: {payment_intent_id} 金额: {payment_intent.amount}")

        # 更新本地记录
        if payment_intent_id in transfers_db:
            transfers_db[payment_intent_id]["status"] = "succeeded"

    # 处理转账成功
    elif event_type == "transfer.created":
        transfer = event.data.object
        transfer_id = transfer.id

        logger.info(f"转账创建: {transfer_id} 金额: {transfer.amount}")

    return JSONResponse(content={"received": True})


# Customer Portal 相关端点
@app.post("/create-portal-session")
async def create_portal_session(request: Request):
    """
    创建 Customer Portal 会话并获取 URL
    
    前端调用目的：
    - 为用户提供完整的订阅管理界面
    - 获取 Stripe 官方的 Customer Portal URL
    - 允许用户管理订阅、支付方式、账单等
    
    使用场景：
    - 用户点击"管理订阅"按钮
    - 需要查看账单历史
    - 更新支付方式
    - 取消或恢复订阅
    """
    try:
        body = await request.json()
        customer_id = body.get("customer_id")
        return_url = body.get("return_url", "http://localhost:8002/portal-return")
        
        if not customer_id:
            raise HTTPException(status_code=400, detail="缺少 customer_id 参数")
        
        # 创建 Customer Portal 会话
        session = stripe.billing_portal.Session.create(
            customer=customer_id,
            return_url=return_url,
            configuration=None  # 使用默认配置
        )
        
        logger.info(f"创建 Customer Portal 会话成功: {session.id} 客户: {customer_id}")
        
        return {
            "session_id": session.id,
            "url": session.url,  # 这就是 Customer Portal 的 URL
            "customer_id": customer_id
        }
        
    except stripe.error.StripeError as e:
        logger.error(f"创建 Customer Portal 会话失败: {str(e)}")
        raise HTTPException(status_code=400, detail=f"创建 Portal 会话失败: {str(e)}")
    except Exception as e:
        logger.error(f"服务器错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@app.get("/portal-return")
async def portal_return():
    """
    Customer Portal返回页面
    前端调用目的：处理用户从Stripe Customer Portal返回后的状态显示
    """
    return {
        "status": "success",
        "message": "订阅管理完成！您的更改已保存。",
        "timestamp": "2024-01-01T00:00:00Z"
    }


# 根路由
@app.get("/")
async def root():
    return {
        "message": "Stripe Connect Account API",
        "description": "用户A通过平台向用户B付款",
        "endpoints": {
            "create_connect_account": "/create-connect-account",
            "get_account_link": "/account-link/{account_id}",
            "get_all_accounts": "/accounts",
            "get_account_info": "/account/{account_id}",
            "create_payment_intent": "/create-payment-intent",
            "create_payment_method": "/create-payment-method",
            "confirm_payment": "/confirm-payment",
            "confirm_card_payment": "/confirm-card-payment",
            "get_payment_intent": "/payment-intent/{payment_intent_id}",
            "payment_return": "/payment/return",
            "create_transfer": "/create-transfer",
            "get_transfers": "/transfers",
            "get_payment_intents": "/payment-intents",
            "webhook": "/stripe-webhook",
            "customer_portal": {
                "create_session": "/create-portal-session",
                "portal_return": "/portal-return"
            }
        },
        "public_key": STRIPE_PUBLIC_KEY
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=8002, reload=True)
